'use client';
import { AppBar, Button, Dialog, Toolbar, Typography } from '@mui/material';
import { useEffect, useRef, useState } from 'react';
import { useActions, useGlobalState } from '@/hooks';
import { showLoading } from '@/components/ContentLoading';
import { getProducts } from '@/services';
import Image from 'next/image';
import './ComparePopup.scss';
import { formatCurrency } from '@/utils/common';
import MyImage from '@/components/MyImage';

const clearStylesFromHtml = (html: string) => {
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/html');
  const styleTags = doc.querySelectorAll('style');
  styleTags.forEach((styleTag: any) => {
    styleTag.remove();
  });
  const allElements = doc.body.querySelectorAll('*');
  allElements.forEach((element: Element) => {
    if (element.hasAttribute('style')) {
      element.removeAttribute('style');
    }
    if (element.hasAttribute('width')) {
      element.removeAttribute('width');
    }
    if (element.hasAttribute('height')) {
      element.removeAttribute('height');
    }
  });
  return doc.body.innerHTML;
};

const compareFields = [
  { field: 'product_image', text: ' ', type: 'image' },
  { field: 'title', text: ' ', type: 'text' },
  {
    field: 'price',
    text: 'Price',
    type: 'currency',
    style: { fontWeight: 700, fontSize: '22px' },
  },
  { field: 'RrpPrice', text: 'RRP', type: 'currency' },
  { field: 'desc', text: 'Description', type: 'html' },
  { field: 'sku', text: 'SKU', type: 'text' },
];

const ComparePopup = () => {
  const [isOnLoading, setIsOnLoading] = useState(true);

  const { compareList } = useGlobalState('product');
  const { userInfo } = useGlobalState('user');
  const [productList, setProductList] = useState<any[]>([]);
  const [cellWidth, setCellWidth] = useState<any>('50%');
  const { removeCompareList, restoreCompareList } = useActions();

  const handleRemoveSku = (e: any) => {
    const dat = e?.currentTarget?.dataset || {};
    removeCompareList({ ...dat });
  };

  const queryList = async (skusArray: string[]) => {
    const hideLoading = showLoading({ inner: false });
    const queryParams = { skus: skusArray.join(',') };
    const skusObj =
      (await getProducts(queryParams).catch(e => {
        void e;
      })) || {};
    hideLoading();
    return skusObj?.result || [];
  };

  const initData = async () => {
    setIsOnLoading(true);
    const skus = await queryList(compareList.map(e => e.sku));
    const newSkus = skus.map((p: any) => ({
      ...p,
      product_image: p.gallery?.at(0) || '',
    }));
    setProductList(newSkus);
    setCellWidth(Math.max(90 / newSkus.length, 10) + '%');
    setIsOnLoading(false);
  };
  const initDataRef = useRef(initData);
  initDataRef.current = initData;

  useEffect(() => {
    compareList?.length && initDataRef.current();
  }, [compareList]);

  const initCompareList = () => {
    const userKey = btoa(userInfo?.email || '');
    restoreCompareList(userKey);
  };
  const initCompareListRef = useRef(initCompareList);
  initCompareListRef.current = initCompareList;
  useEffect(() => {
    initCompareListRef.current();
  }, []);

  const handlePrint = () => {
    window.print();
  };
  const handleClose = () => {
    window.close();
  };

  return (
    <div className="compare-page">
      <div className="compare-page-header non-printable">
        <div className="compare-page-title">Compare Products</div>
        <div className="compare-page-buttons">
          <span className="compare-page-button-print" onClick={handlePrint}>
            <i className="iconfont icon-print"></i>
            Print This Page
          </span>
          <button
            className="compare-page-button-close"
            autoFocus
            onClick={handleClose}
          >
            <span className="iconfont icon-close"></span>
          </button>
        </div>
      </div>
      <div className="compare-page-content">
        {productList?.length > 0 ? (
          <table className="compare-page-table">
            <tbody>
              <tr className="compare-page-table-row non-printable">
                <td className="compare-page-table-title"></td>
                {productList.map((P: any, idx: number) => (
                  <td
                    key={idx}
                    style={{ textAlign: 'right' }}
                    className="compare-page-table-cell-toolbar"
                  >
                    <button
                      className="compare-page-button-remove"
                      data-sku={P.sku}
                      onClick={handleRemoveSku}
                    >
                      <span className="button-text">remove</span>
                      <span className="iconfont icon-close"></span>
                    </button>
                  </td>
                ))}
              </tr>
              {compareFields.map((CF: any) => (
                <tr key={CF.field} className="compare-page-table-row">
                  <td
                    className="compare-page-table-title"
                    style={{ width: '10%' }}
                  >
                    <div className="cell-content">{CF.text}</div>
                  </td>
                  {productList.map((P: any) => (
                    <td
                      key={P.sku + '' + CF.field}
                      className="compare-page-table-cell"
                      style={{
                        width: cellWidth,
                        maxWidth: cellWidth,
                      }}
                    >
                      <div
                        className={
                          'cell-content ' +
                          (CF.type ? 'content-type-' + CF.type : '')
                        }
                        style={{ ...(CF.style ? CF.style : {}) }}
                      >
                        {CF.type == 'image' ? (
                          <div className="compare-page-image-wrapper">
                            <MyImage
                              fill={true}
                              sizes={'100%'}
                              priority={true}
                              src={P.product_image}
                              alt={''}
                              className="compare-page-image"
                            />
                          </div>
                        ) : CF.field == 'price' ? (
                          <span className="compare-page-price">
                            {P.special_price ? (
                              <>
                                {formatCurrency(P.special_price)}
                                <div className="price-promotion">
                                  <span className="price-regular">
                                    Regular: {formatCurrency(P.price)}
                                  </span>
                                  <span className="price-discount">
                                    {Number(
                                      (100 * (P.price - P.special_price)) /
                                        P.price
                                    ).toFixed(0)}
                                    % off
                                  </span>
                                </div>
                              </>
                            ) : (
                              formatCurrency(P.price)
                            )}
                          </span>
                        ) : CF.type == 'currency' ? (
                          <span>{formatCurrency(P[CF.field])}</span>
                        ) : CF.type == 'html' ? (
                          <div
                            className="compare-page-html"
                            dangerouslySetInnerHTML={{
                              __html: clearStylesFromHtml(P[CF.field]),
                            }}
                          ></div>
                        ) : (
                          <span className="compare-page-text">
                            {P[CF.field]}
                          </span>
                        )}
                      </div>
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          !isOnLoading && (
            <div className="compare-page-nulltips">
              You have no products to compare.
            </div>
          )
        )}
      </div>
    </div>
  );
};

export default ComparePopup;
